package com.weetop.cfw.register

import android.os.Bundle
import android.text.Editable
import android.text.InputType
import android.text.TextWatcher
import android.view.View
import android.widget.Toast
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.EncryptUtils
import com.weetop.cfw.MainActivity
import com.weetop.cfw.R
import com.weetop.cfw.base.presenter.imp.ForgetPasswordPresenterImp
import com.weetop.cfw.base.presenter.imp.PasswordLogInPresenterImp
import com.weetop.cfw.base.ui.activity.CommonBaseActivity
import com.weetop.cfw.base.view.ForgetPasswordView
import com.weetop.cfw.base.view.PasswordLogInView
import com.weetop.cfw.bean.ErrorBean
import com.weetop.cfw.bean.LogInBean
import com.weetop.cfw.bean.VerificationCodeBean
import com.weetop.cfw.constants.UrlConstants
import com.weetop.cfw.event.UpdateUserInfoEvent
import com.weetop.cfw.log_in.PasswordLogInActivity
import com.weetop.cfw.other.CommonWebViewActivity
import com.weetop.cfw.utils.EventBusUtils
import com.weetop.cfw.utils.MMKVUtils
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_forget_password.*
import kotlinx.android.synthetic.main.activity_forget_password.editPhoneNumber
import kotlinx.android.synthetic.main.activity_forget_password.editVerificationCode
import kotlinx.android.synthetic.main.activity_forget_password.select
import kotlinx.android.synthetic.main.activity_forget_password.textGetVerificationCode
import kotlinx.android.synthetic.main.activity_forget_password.textPrivacyPolicy
import kotlinx.android.synthetic.main.activity_forget_password.textUseProtocol
import kotlinx.android.synthetic.main.activity_register.*
import java.util.concurrent.TimeUnit


/**
 * 忘记密码界面
 */
class ForgetPasswordActivity : CommonBaseActivity(), View.OnClickListener, TextWatcher,
    ForgetPasswordView,
    PasswordLogInView {


    private var isPassword = true
    private var isPasswordAgain = true

    private lateinit var forgetPasswordPresenterImp: ForgetPasswordPresenterImp
    private lateinit var passwordLogInPresenterImp: PasswordLogInPresenterImp

    private var dispose: Disposable? = null
    private var IsSelect: Int = 0

    override fun getLayoutId() = R.layout.activity_forget_password

    override fun initView(savedInstanceState: Bundle?) {
        forgetPasswordPresenterImp = ForgetPasswordPresenterImp()
        forgetPasswordPresenterImp.attachView(this)
        passwordLogInPresenterImp = PasswordLogInPresenterImp()
        passwordLogInPresenterImp.attachView(this)
        setViewsOnClickListener(
            this,
            textGetVerificationCode,
            textAtOnceFindBack,
            textPasswordLogIn,
            textAccountRegister,
            imageForgetPasswordBack,
            textUseProtocol,
            textPrivacyPolicy,
            imageShowOrHidePasswordAgain,
            imageShowOrHidePassword,
            imageClearVerificationCode,
            select
        )
        editVerificationCode.addTextChangedListener(this)
    }

    override fun initData(savedInstanceState: Bundle?) {
    }


    override fun logInSuccess(logInBean: LogInBean?) {
        if (logInBean != null) {
            showNativeShortToast("登录成功")
            MMKVUtils.saveToken(logInBean.token)
            MMKVUtils.saveUlevel(logInBean.ulevel)
            EventBusUtils.post(logInBean)
            EventBusUtils.post(UpdateUserInfoEvent())
            ActivityUtils.finishActivity(this)
//            ActivityUtils.startActivity(MainActivity::class.java)
        }
    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.textGetVerificationCode -> forgetPasswordPresenterImp.getVerificationCode(
                this@ForgetPasswordActivity,
                editPhoneNumber.text.toString().trim()
            )
            R.id.textAtOnceFindBack -> {

                if (IsSelect == 0) {
                    Toast.makeText(context, "请仔细阅读并同意用户协议", Toast.LENGTH_SHORT).show()
                    return
                }
                forgetPasswordPresenterImp.resetPassword(
                    this@ForgetPasswordActivity,
                    editPhoneNumber.text.toString().trim(),
                    EncryptUtils.encryptMD5ToString(editPassword.text.toString().trim())
                        .toLowerCase(),
                    EncryptUtils.encryptMD5ToString(editPasswordAgain.text.toString().trim())
                        .toLowerCase(),
                    editVerificationCode.text.toString().trim()
                )

            }
            R.id.textPasswordLogIn -> ActivityUtils.startActivity(PasswordLogInActivity::class.java)
            R.id.textAccountRegister -> ActivityUtils.startActivity(RegisterActivity::class.java)
            R.id.imageForgetPasswordBack -> ActivityUtils.finishActivity(this)
            R.id.textUseProtocol -> CommonWebViewActivity.startCommonWebViewActivity(
                this,
                UrlConstants.use_protocol_web_url
            )
            R.id.textPrivacyPolicy -> CommonWebViewActivity.startCommonWebViewActivity(
                this,
                UrlConstants.privacy_policy_web_url
            )
            R.id.imageShowOrHidePassword -> {
                if (isPassword) {
                    editPassword.inputType = InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
                    isPassword = false
                    imageShowOrHidePassword.setImageResource(R.mipmap.password_hide_logo)
                } else {
                    editPassword.inputType =
                        InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
                    isPassword = true
                    imageShowOrHidePassword.setImageResource(R.mipmap.password_show_logo)
                }
            }
            R.id.imageShowOrHidePasswordAgain -> {
                if (isPasswordAgain) {
                    editPasswordAgain.inputType = InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
                    isPasswordAgain = false
                    imageShowOrHidePasswordAgain.setImageResource(R.mipmap.password_hide_logo)
                } else {
                    editPasswordAgain.inputType =
                        InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
                    isPasswordAgain = true
                    imageShowOrHidePasswordAgain.setImageResource(R.mipmap.password_show_logo)
                }
            }
            R.id.imageClearVerificationCode -> editVerificationCode.setText("")
            R.id.select -> {
                if (IsSelect == 0) {
                    IsSelect = 1
                    select.setImageResource(R.mipmap.select_t);
                } else {
                    IsSelect = 0
                    select.setImageResource(R.mipmap.select_f);
                }
            }
        }
    }

    override fun afterTextChanged(p0: Editable?) {
        if (p0 != null) {
            if (p0.toString().isNotEmpty()) {
                imageClearVerificationCode.visibility = View.VISIBLE
            } else {
                imageClearVerificationCode.visibility = View.INVISIBLE
            }
        }
    }

    override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

    }

    override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

    }

    override fun onDestroy() {
        super.onDestroy()
        forgetPasswordPresenterImp.detachView()
        if (dispose != null && !dispose!!.isDisposed) {
            dispose!!.dispose()
        }
    }

    /**
     * 获取验证码成功
     */
    override fun getVerificationCodeSuccess(verificationCodeBean: VerificationCodeBean?) {
        showNativeShortToast(verificationCodeBean?.message)
        dispose = Observable.interval(1, TimeUnit.SECONDS)
            .take(61)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                if ((60 - it) == 0L) {
                    textGetVerificationCode.text = "发送验证码"
                    textGetVerificationCode.setTextColor(ColorUtils.getColor(R.color.c_1381CC))
                    textGetVerificationCode.isEnabled = true
                } else {
                    textGetVerificationCode.isEnabled = false
                    textGetVerificationCode.setTextColor(ColorUtils.getColor(R.color.secondary_text_color))
                    textGetVerificationCode.text = "${60 - it}秒后重新发送"
                }
            }
    }

    /**
     * 获取验证码失败
     */
    override fun getVerificationCodeFailed(verificationCodeBean: VerificationCodeBean?) {
        showNativeShortToast(verificationCodeBean?.message)
    }

    /**
     * 密码找回成功
     */
    override fun resetPasswordSuccess(errorBean: ErrorBean?) {
        showNativeShortToast("密码找回成功")
        passwordLogInPresenterImp.passwordLogIn(
            this@ForgetPasswordActivity,
            editPhoneNumber.text.toString().trim(),
            EncryptUtils.encryptMD5ToString(editPassword.text.toString().trim()).toLowerCase()
        )

    }
}
